<!--用户树-->
<template>
  <el-tree
    v-loading="treeLoading"
    class="common-el-tree"
    :data="userListData"
    :props="defaultUserProps"
    node-key="id"
    default-expand-all
    :expand-on-click-node="false"
    @node-click="handleUserNodeClick">
    <div slot-scope="{ node,data }" class="custom-tree-node">
      <i v-if="data.level==1" class="el-icon-user-solid" />
      <span v-if="data.level==0" class="text" style="font-weight: bold;">{{ node.label }} <span style="font-size:12px;font-weight: normal;">({{ data.children.length }}人)</span></span>
      <span v-if="data.level==1" class="text">{{ node.label }} <span style="font-size:12px">{{ data.job?(data.job.split(':')[1]) :'' }} {{ data.mobile }}</span></span>
    </div>
  </el-tree>
</template>
<script>
export default {
  props: {
    isFilterInput: { type: Boolean, default: false } // 隐藏节点过滤
  },
  data() {
    return {
      searchValue: '',
      selectedValue: '',
      defaultUserProps: {
        children: 'children',
        label: 'label'
      },
      userListData: [],
      treeLoading: false
    }
  },
  watch: {
    searchValue(val) {
      this.$refs.tree.filter(val)
    },
    selectedValue: function(val) {
      this.$emit('input', typeof (val) === 'string' ? val : val.join(';'))
    },
    value: function(val) {
      setTimeout(() => {
        this.selectedValue = val
      }, 200)
    }
  },
  mounted() {},
  created() {
  },
  methods: {
    init() {
      this.fetchUserList()
    },
    async fetchUserList() {
      const response = await this.$store.dispatch('userList', {})
      var userList = []
      for (var item in response) {
        var obj = {
          id: item,
          level: 0,
          label: item.toUpperCase(),
          children: response[item].filter(item => { item.label = item.realName; item.level = 1; return true })
        }
        userList.push(obj)
      }
      userList.reverse()
      this.userListData = userList
      if (this.userListData.length > 0) {
        if (this.userListData[0].children.length > 0) {
          this.handleUserNodeClick(this.userListData[0].children[0])
        }
      }
    },
    handleUserNodeClick(data) {
      if (data.level !== 1) {
        return
      }
      this.$emit('nodeClick', { id: data.id, realName: data.realName, userName: data.userName })
      this.selectedValue = data.id
    },
    /* 节点过滤函数 */
    onTreeFilter(value, data) {
      if (!value) return true
      return data[this.defaultTreeProps.filter] ? data[this.defaultTreeProps.label].indexOf(value) !== -1 || data[this.defaultTreeProps.filter].indexOf(value.toUpperCase()) !== -1 : data[this.defaultTreeProps.label].indexOf(value) !== -1
    }
  }
}
</script>
<style lang="scss" scoped />
